<body>
<header>
    <h2>Web APIs<h2>
</header>
<div class="web-api-cnt">
    <div class="web-api-card">
        <div class="web-api-card-head"> Demo - Audio </div>
        <div class="web-api-card-body">
            <div id="error" class="close"></div>
            <div>
                <audio controls src="./lovely.mp4" id="audio"></audio>
            </div>
            <div>
                <button onclick="audioFromAudioFile.init()">Init</button>
                <button onclick="audioFromAudioFile.play()">Play</button>
                <button onclick="audioFromAudioFile.pause()">Pause</button>
                <button onclick="audioFromAudioFile.stop()">Stop</button>
            </div>
            <div>
                    <span>Vol: <input onchange="audioFromAudioFile.changeVolume()" type="range" id="vol" min="1" max="3"
                                      step="0.01" value="1" /></span>
                <span>Pan: <input onchange="audioFromAudioFile.changePan()" type="range" id="panner" min="-1"
                                  max="1" step="0.01" value="0" /></span>
            </div>
        </div>
    </div>
</div>
</body>
<script>
  const l = console.log
  let audioFromAudioFile = (function () {
    var audioContext
    var volNode
    var pannerNode
    var mediaSource

    function init() {
      l("Init")
      try {

        audioContext = new AudioContext()
        mediaSource = audioContext.createMediaElementSource(audio)
        volNode = audioContext.createGain()
        volNode.gain.value = 1
        pannerNode = new StereoPannerNode(audioContext, { pan: 0 })

        mediaSource.connect(volNode).connect(pannerNode).connect(audioContext.destination)
        console.log(volNode)
      }
      catch (e) {
        error.innerHTML = "The Web Audio API is not supported in this device."
        error.classList.remove("close")
      }
    }
    function play() {
      audio.play()
    }

    function pause() {
      audio.pause()
    }

    function stop() {
      audio.stop()
    }

    function changeVolume() {
      volNode.gain.value = document.getElementById('vol').value
    }

    function changePan() {
      pannerNode.gain.value = tdocument.getElementById('panner').value
    }

    return {
      init,
      play,
      pause,
      stop,
      changePan,
      changeVolume
    }
  })()
</script>
